class PostfixExpression:
    """
    后缀表达式
    参数：
    expression: 传入正常的表达式
    函数：
    initAns: 初始化后缀表达式
    val: 计算后缀表达式
    all: 对所有的函数进行最后的封装
    """
    def all(self, expression):
        ans = self.initAns(expression)
        return self.val(ans)

    def initAns(self, expression):
        stack = []
        ans = []
        d = {
            '*': 3,
            '/': 3,
            '+': 2,
            '-': 2,
            '(': 1,
        }
        tem = expression.split(" ")
        print(tem)
        for i in tem:
            if i.isdigit():
                ans.append(i)
            elif i == '(':
                stack.append(i)
            elif i == ')':
                tem = stack.pop()
                while tem != '(':
                    ans.append(tem)
                    tem = stack.pop()
            else:
                while stack and d[i] <= d[stack[-1]]:
                    ans.append(stack.pop())
                stack.append(i)
        while stack:
            ans.append(stack.pop())
        return ans

    def val(self, ans):
        def op(m, a, b):
            if m == "*":
                return a * b
            if m == "+":
                return a + b
            if m == "-":
                return a - b
            if m == "/":
                return a / b

        stack = []
        for i in range(len(ans)):
            if ans[i].isdigit():
                stack.append(ans[i])
            else:
                stack.append(op(ans[i], int(stack[0]), int(stack[1])))
                stack.pop(0)
                stack.pop(0)
        return stack[0]


t = PostfixExpression()
print(t.all('1 + 2 + 3'))
